"use client";

import { tagApi } from '@/constants';
import { get, post, put, patch, del } from '@/util/api';

// 标签基本信息接口
export interface TagBase {
  name: string;
  description?: string;
  color?: string;
  icon?: string;
  sort?: number;
  isActive?: number;
}

// 标签响应接口
export interface Tag extends TagBase {
  id: number;
  usageCount: number;  // 使用次数（与后端保持一致）
  articleCount?: number;  // 兼容旧的字段名
  createdAt: string;
  updatedAt: string;
}

// 标签列表响应接口
export interface TagListResponse {
  data: Tag[];
  total: number;
  page?: number;
  pageSize?: number;
}

/**
 * 标签管理服务类
 * 封装所有标签相关的API调用
 */
class TagService {
  /**
   * 获取标签列表
   * @param params 查询参数
   * @returns Promise<Tag[] | TagListResponse>
   */
  async getTagList(params?: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    isActive?: number;
    orderBy?: 'createdAt' | 'articleCount' | 'sort';
    orderDirection?: 'asc' | 'desc';
  }): Promise<Tag[] | TagListResponse> {
    try {
      const response = await get(tagApi.LIST, {params});
      return (response.data || response) as Tag[];
    } catch (error) {
      console.error('获取标签列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取标签详情
   * @param id 标签ID
   * @returns Promise<Tag>
   */
  async getTagDetail(id: number): Promise<Tag> {
    try {
      const response = await get(tagApi.DETAIL(id));
      return (response.data || response) as Tag;
    } catch (error) {
      console.error(`获取标签详情失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 创建标签
   * @param tagData 标签数据
   * @returns Promise<Tag>
   */
  async createTag(tagData: Partial<TagBase>): Promise<Tag> {
    try {
      const response = await post(tagApi.CREATE, tagData);
      return (response.data || response) as Tag;
    } catch (error) {
      console.error('创建标签失败:', error);
      throw error;
    }
  }

  /**
   * 更新标签
   * @param id 标签ID
   * @param tagData 标签数据
   * @returns Promise<Tag>
   */
  async updateTag(id: number, tagData: Partial<TagBase>): Promise<Tag> {
    try {
      const response = await patch(tagApi.UPDATE(id), tagData);
      return (response.data || response) as Tag;
    } catch (error) {
      console.error(`更新标签失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 更新标签状态
   * @param id 标签ID
   * @param isActive 状态值
   * @returns Promise<Tag>
   */
  async updateTagStatus(id: number, isActive: number): Promise<Tag> {
    try {
      const response = await patch(tagApi.UPDATE_STATUS(id), { isActive });
      return (response.data || response) as Tag;
    } catch (error) {
      console.error(`更新标签状态失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 删除标签
   * @param id 标签ID
   */
  async deleteTag(id: number): Promise<void> {
    try {
      await del(tagApi.DELETE(id));
    } catch (error) {
      console.error(`删除标签失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 批量操作标签
   * @param ids 标签ID数组
   * @param action 操作类型
   * @param data 额外数据
   * @returns Promise<any>
   */
  async batchOperateTags(ids: number[], action: string, data?: any): Promise<unknown> {
    try {
      const response = await patch(tagApi.BATCH_OPERATE, { ids, action, ...data });
      return (response.data || response) as unknown;
    } catch (error) {
      console.error('批量操作标签失败:', error);
      throw error;
    }
  }

  /**
   * 获取热门标签
   * @param limit 限制数量
   * @returns Promise<Tag[]>
   */
  async getPopularTags(limit: number = 10): Promise<Tag[]> {
    try {
      const response = await get(tagApi.POPULAR, { params: { limit } });
      return (response.data || response || []) as Tag[];
    } catch (error) {
      console.error('获取热门标签失败:', error);
      return []; // 失败时返回空数组，避免影响页面加载
    }
  }

  /**
   * 导入标签
   * @param tagsData 标签数据数组
   * @returns Promise<{ imported: number; failed: number; details: any }>
   */
  // async importTags(tagsData: TagBase[]): Promise<{ imported: number; failed: number; details: any }> {
  //   try {
  //     const response = await post(tagApi.IMPORT, { tags: tagsData });
  //     return response.data || response;
  //   } catch (error) {
  //     console.error('导入标签失败:', error);
  //     throw error;
  //   }
  // }

  /**
   * 导出标签
   * @param format 导出格式
   * @param params 查询参数
   * @returns Promise<Blob>
   */
  // async exportTags(format: 'json' | 'csv' | 'excel' = 'json', params?: {
  //   isActive?: number;
  // }): Promise<Blob> {
  //   try {
  //     const response = await get(tagApi.EXPORT, { format, ...params }, {
  //       responseType: 'blob',
  //     });
  //     return response.data || response;
  //   } catch (error) {
  //     console.error('导出标签失败:', error);
  //     throw error;
  //   }
  // }

  /**
   * 检查标签名称是否已存在
   * @param name 标签名称
   * @param excludeId 排除的标签ID（用于更新时）
   * @returns Promise<{ exists: boolean }>
   */
  // async checkTagNameExists(name: string, excludeId?: number): Promise<{ exists: boolean }> {
  //   try {
  //     const response = await get(tagApi.CHECK_NAME, { name, excludeId });
  //     return response.data || response;
  //   } catch (error) {
  //     console.error('检查标签名称是否存在失败:', error);
  //     throw error;
  //   }
  // }
}

// 导出标签服务实例
export const tagService = new TagService();
export default tagService;